<template>
  <div class="register-page">
    <div class="register-container">
      <div class="step-progress">
        <div class="step-track">
          <div class="step-progress-bar" :style="{ width: progressWidth }"></div>
        </div>
        <div class="step-labels">
          <div 
            v-for="(step, index) in steps" 
            :key="index" 
            class="step-label"
            :class="{ 'active': currentStep > index, 'completed': currentStep > index + 1 }"
          >
            {{ step }}
          </div>
        </div>
      </div>

      <div class="form-section">
        <div v-if="currentStep === 1" class="step-content step1">
          <!-- 用户名输入框 -->
          <div class="form-item">
            <label class="label">用户名</label>
            <input 
              type="text" 
              class="phone-input input-step1" 
              placeholder="请输入用户名" 
              v-model="userName"
              maxlength="12"
              @input="validateUserName"
            >
          </div>
          <div v-if="userNameError" class="error-message">{{ userNameError }}</div>

          <div class="form-item">
            <label class="label">手机号</label>
            <select class="country-code">
              <option value="86">中国大陆 86</option>
            </select>
            <input 
              type="tel" 
              class="phone-input input-step1" 
              placeholder="有效手机号" 
              v-model="phone"
              maxlength="11"
              @input="validatePhone"
            >
          </div>
          <div v-if="phoneError" class="error-message">{{ phoneError }}</div>

          <div class="form-item">
            <label class="label">短信验证码</label>
            <input 
              type="text" 
              class="code-input input-step1" 
              placeholder="6位数字" 
              v-model="code"
              maxlength="6"
            >
            <button 
              class="send-code-btn btn-step1" 
              @click="sendVerificationCode"
              :disabled="!isUserNameValid || !isPhoneValid || isCountingDown"
            >
              {{ codeBtnText }}
            </button>
          </div>

          <div class="agreement agr-step1">
            <input type="checkbox" v-model="agree" id="agreement1">
            <label for="agreement1">同意《服务协议》和《隐私政策》</label>
          </div>

          <button 
            class="next-btn btn-step1" 
            :disabled="!isUserNameValid || !isPhoneValid || !code || !agree"
            @click="goToNextStep"
          >
            下一步，设置密码
          </button>
        </div>

        <div v-else-if="currentStep === 2" class="step-content step2">
          <div class="form-item">
            <label class="label label-step2">设置密码</label>
            <input 
              type="password" 
              class="input-step2" 
              v-model="password" 
              placeholder="请设置密码（需包含字母和数字）"
              @input="validatePassword"
            >
          </div>
          <div v-if="passwordError" class="error-message error-step2">{{ passwordError }}</div>

          <div class="form-item">
            <label class="label label-step2">确认密码</label>
            <input 
              type="password" 
              class="input-step2" 
              v-model="confirmPassword" 
              placeholder="请确认密码"
              @input="validateConfirmPassword"
            >
          </div>
          <div v-if="confirmError" class="error-message error-step2">{{ confirmError }}</div>

          <button 
            class="next-btn btn-step2" 
            @click="goToNextStep"
            :disabled="!isPasswordValid || !isConfirmValid"
          >
            下一步，完成注册
          </button>
        </div>

        <div v-else-if="currentStep === 3" class="step-content step3">
          <div class="success-tip tip-step3">注册成功！</div>
          <div class="success-desc desc-step3">您的账号已激活，可直接登录使用</div>
          <button class="next-btn btn-step3" @click="goToLogin">前往登录</button>
        </div>

        <div class="enterprise-register">
          <a href="#">企业客户注册</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { registerApi } from '@/api/users.js'; 


const router = useRouter();

// 用户名相关变量
const userName = ref('');
const userNameError = ref('');
const isUserNameValid = ref(false);

// 其他变量
const steps = ref(['验证手机', '设置密码', '注册成功']);
const currentStep = ref(1);
const phone = ref('');
const code = ref('');
const agree = ref(false);
const password = ref('');
const confirmPassword = ref('');
const codeBtnText = ref('发送验证码');
const phoneError = ref('');
const passwordError = ref('');
const confirmError = ref('');
const isPhoneValid = ref(false);
const isPasswordValid = ref(false);
const isConfirmValid = ref(false);
const isCountingDown = ref(false);
let countdownTimer = null;

// 进度条计算
const progressWidth = computed(() => {
  const totalSteps = steps.value.length - 1;
  const progress = (currentStep.value - 1) / totalSteps;
  return `${progress * 100}%`;
});

const validateUserName = () => {
  // 允许中文、字母、数字、下划线，长度2~16
  const userNameReg = /^[\u4e00-\u9fa5_a-zA-Z0-9]{2,16}$/;
  if (!userName.value) {
    userNameError.value = '请输入用户名';
    isUserNameValid.value = false;
  } else if (!userNameReg.test(userName.value)) {
    userNameError.value = '用户名需为2-16位，可包含中文、字母、数字和下划线';
    isUserNameValid.value = false;
  } else {
    userNameError.value = '';
    isUserNameValid.value = true;
  }
};

// 手机号验证
const validatePhone = () => {
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phone.value) {
    phoneError.value = '请输入手机号';
    isPhoneValid.value = false;
  } else if (!phoneReg.test(phone.value)) {
    phoneError.value = '请输入有效的中国手机号';
    isPhoneValid.value = false;
  } else {
    phoneError.value = '';
    isPhoneValid.value = true;
  }
};

// 密码验证
const validatePassword = () => {
  const passwordReg = /^(?=.*[0-9])(?=.*[a-zA-Z]).{6,}$/;
  if (!password.value) {
    passwordError.value = '请设置密码';
    isPasswordValid.value = false;
  } else if (!passwordReg.test(password.value)) {
    passwordError.value = '密码必须包含数字和字母，且长度至少6位';
    isPasswordValid.value = false;
  } else {
    passwordError.value = '';
    isPasswordValid.value = true;
    validateConfirmPassword();
  }
};

// 确认密码验证
const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    confirmError.value = '请确认密码';
    isConfirmValid.value = false;
  } else if (confirmPassword.value !== password.value) {
    confirmError.value = '两次输入的密码不一致';
    isConfirmValid.value = false;
  } else {
    confirmError.value = '';
    isConfirmValid.value = true;
  }
};

// 发送验证码
const sendVerificationCode = () => {
  if (!isUserNameValid.value) {
    ElMessage.warning('请先输入有效的用户名');
    return;
  }
  if (!isPhoneValid.value) {
    ElMessage.warning('请先输入有效的手机号');
    return;
  }

  ElMessage.success('验证码已发送至您的手机（模拟）');
  
  let countdown = 60;
  isCountingDown.value = true;
  codeBtnText.value = `${countdown}s后重新发送`;
  
  countdownTimer = setInterval(() => {
    countdown--;
    codeBtnText.value = `${countdown}s后重新发送`;
    if (countdown <= 0) {
      clearInterval(countdownTimer);
      codeBtnText.value = '发送验证码';
      isCountingDown.value = false;
    }
  }, 1000);
};

// 下一步逻辑
const goToNextStep = () => {
  if (currentStep.value === 1) {
    if (!isUserNameValid.value) {
      ElMessage.warning('请输入有效的用户名');
      return;
    }
    if (!isPhoneValid.value) {
      ElMessage.warning('请输入有效的手机号');
      return;
    }
    if (!agree.value) {
      ElMessage.warning('请同意服务协议和隐私政策');
      return;
    }
    currentStep.value++;
  } 
  else if (currentStep.value === 2) {
    if (!isPasswordValid.value || !isConfirmValid.value) {
      ElMessage.warning('请完善密码信息并确保两次输入一致');
      return;
    }

    const userData = {
      userName: userName.value,
      phone: phone.value,
      password: password.value
    };

    registerApi(userData)
      .then(response => {
        if (response.data.code === 200) {
          ElMessage.success('注册成功！即将跳转到登录页');
          currentStep.value++; 
          setTimeout(() => {
            router.push('/login');
          }, 2000);
        } else {
          ElMessage.error(response.data.msg || '注册失败，请重试');
        }
      })
      .catch(error => {
        console.error('注册接口错误：', error);
        const errorMsg = error.response?.data?.msg || '手机号不可重复';
        ElMessage.error(errorMsg);
      });
  }
};

// 前往登录
const goToLogin = () => {
  router.push('/login');
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) clearInterval(countdownTimer);
});
</script>

<style scoped>
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
  background-image: url(../images/pc_login_bg.png) ;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.register-container {
  width: 500px;
  height: 620px;
  max-width: 100%;
  min-height: 620px;
  padding: 35px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  box-sizing: border-box;
  border: 1px solid #f0f0f0;
}

.step-progress {
  width: 100%;
  height: 40px;
  margin-bottom: 25px;
  position: relative;
}

.step-track {
  position: absolute;
  top: 10px;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: #e8e8e8;
  border-radius: 2px;
}

.step-progress-bar {
  height: 100%;
  background-color: #67c23a;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.step-labels {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.step-label {
  font-size: 14px;
  color: #999;
}

.step-label.active,
.step-label.completed {
  color: #67c23a;
  font-weight: 500;
}

.form-section {
  width: 100%;
  height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
}

.step-content {
  width: 100%;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.country-code {
  height: 42px;
  padding: 0 14px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
  box-sizing: border-box;
  margin-right: -1px;
}

.step1 {
  padding-top: 10px;
}
.step1 .form-item {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
}
.step1 .label {
  width: 90px;
  text-align: right;
  margin-right: 18px;
  font-size: 14px;
  color: #333;
}
.input-step1 {
  height: 42px;
  padding: 0 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  flex-grow: 1;
  box-sizing: border-box;
}
.code-input.input-step1 {
  margin-right: 8px;
  border-radius: 4px 0 0 4px;
}
.btn-step1 {
  height: 42px;
  padding: 0 18px;
  font-size: 14px;
  border-radius: 0 4px 4px 0;
  border: 1px solid #ddd;
  background: #fff;
  color: #666;
  cursor: pointer;
}
.btn-step1:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}
.agr-step1 {
  margin: 25px 0 25px 108px;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
}
.agr-step1 input {
  margin-right: 6px;
}
.step1 .next-btn {
  margin-left: 63px;
  width: calc(100% - 108px);
  height: 44px;
  background: #ff7d00;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}
.step1 .error-message {
  margin-left: 108px;
  color: #c13d3d;
  font-size: 12px;
  height: 16px;
  margin-top: -16px;
  margin-bottom: 8px;
}

.step2 {
  padding-top: 40px;
}
.step2 .form-item {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
}
.label-step2 {
  width: 65px;
  text-align: right;
  margin-right: 23px;
  font-size: 14px;
  color: #333;
}
.input-step2 {
  height: 44px;
  padding: 0 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  flex-grow: 1;
  box-sizing: border-box;
}
.error-step2 {
  margin-left: 88px;
  color: #f56c6c;
  font-size: 12px;
  height: 16px;
  margin-top: -14px;
  margin-bottom: 8px;
}
.step2 .next-btn {
  margin-left: 88px;
  width: calc(100% - 88px);
  height: 44px;
  background: #ff7d00;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 15px;
}

.step3 {
  padding-top: 120px;
  align-items: center;
}
.tip-step3 {
  font-size: 26px;
  color: #67c23a;
  margin-bottom: 12px;
}
.desc-step3 {
  font-size: 14px;
  color: #666;
  margin-bottom: 60px;
}
.step3 .next-btn {
  width: 220px;
  height: 44px;
  background: #ff7d00;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-left: 0;
}

.enterprise-register {
  margin-top: auto;
  text-align: center;
  padding-top: 20px;
  font-size: 14px;
}
.enterprise-register a {
  color: #409eff;
  text-decoration: none;
}
.enterprise-register a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .register-container {
    padding: 20px 15px;
  }
  .step1 .form-item,
  .step2 .form-item {
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 20px;
  }
  .step1 .label,
  .label-step2 {
    width: 100%;
    text-align: left;
    margin-right: 0;
    margin-bottom: 6px;
  }
  .country-code {
    width: 100%;
    border-radius: 4px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  .input-step1,
  .input-step2 {
    width: 100%;
    margin-right: 0;
  }
  .code-input.input-step1 {
    border-radius: 4px;
    margin-bottom: 10px;
  }
  .btn-step1 {
    width: 100%;
    border-radius: 4px;
  }
  .step1 .error-message,
  .error-step2,
  .agr-step1 {
    margin-left: 0;
  }
  .step1 .next-btn,
  .step2 .next-btn {
    width: 100%;
    margin-left: 0;
  }
  .step3 {
    padding-top: 80px;
  }
}
</style>
